const path = require("path");
const {merge} = require("webpack-merge");
const baseConfig = require("./webpack.base.js");
const HappyPack = require("happypack");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");
const CSSMinimizerPlugin = require("css-minimizer-webpack-plugin");
const HtmlWebpackInjectAttributesPlugin = require("html-webpack-inject-attributes-plugin");
const TerserPlugin = require("terser-webpack-plugin");
const os = require("os");

const happypackCommonConfig = {
  debug: false,
  threadPool: HappyPack.ThreadPool({ size: os.cpus().length }),
};

const webpackProdConfig = merge(baseConfig, {
  mode: "production",
  output: {
    filename: "js/[name].[contenthash:8].bundle.js",
    path: path.join(process.cwd(), "./app/public/dist/prod"),
    publicPath: "/dist/prod",
    crossOriginLoading: "anonymous",
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, "happypack/loader?id=css"],
      },
      {
        test: /\.js$/,
        include: [path.resolve(process.cwd(), "./app/pages")],
        use: ["happypack/loader?id=js"],
      },
    ],
  },
  performance: {
    hints: false,
  },
  plugins: [
    new CleanWebpackPlugin(["public/dist"], {
      root: path.resolve(process.cwd(), "./app"),
      exclude: [],
      verbose: true,
      dry: false,
    }),
    new MiniCssExtractPlugin({
      chunkFilename: "css/[name]_[contenthash:8].bundle.css",
    }),
    new CSSMinimizerPlugin(),
    new HappyPack({
        ...happypackCommonConfig,
        id: 'js',
        loaders: [`babel-loader?${JSON.stringify({
            presets: ['@babel/preset-env'],
            plugins: ['@babel/plugin-transform-runtime'],
        })}`],
    }),
    new HappyPack({
        ...happypackCommonConfig,
        id: 'css',
        loaders: [{
            path: 'css-loader',
            options: {
                importLoaders: 1,
            }, 
        }],
    }),
    new HtmlWebpackInjectAttributesPlugin({
        crossorigin: 'anonymous',
    })
  ],
  optimization: {
    minimize: true,
    minimizer: [
        new TerserPlugin({
            parallel: true,
            terserOptions: {
                compress: {
                    drop_console: true,
                },
            },
        }),
    ],
  },
});

module.exports = webpackProdConfig;
